import React from 'react';
import { connect } from 'dva';
import { Tabs } from 'antd';
import router from 'umi/router';
import withRouter from 'umi/withRouter';
import './index.styl';

const { TabPane } = Tabs;

function HeaderTabs(props) {
  const onChange = (value) => {
    const path = panes.find(item => item.key === value)
    router.push({
      pathname: path.path,
      query: path.query
    })
  };

  const onEdit = (targetKey, action) => {
    // 清除设备维修模块本地缓存数据
    if (targetKey === '/deviceRepair') {
      localStorage.removeItem('repairSingle')
      localStorage.removeItem('reformSingle')
      localStorage.removeItem('complainSingle')
      localStorage.removeItem('formData')
      localStorage.removeItem('reformData')
      localStorage.removeItem('complainData')
      localStorage.removeItem('repairTabsKey')
    }
    // 清除工作台页码缓存
    if (targetKey === '/workBench') {
      localStorage.removeItem('workBenchPage')
    }
    const {
      dispatch,
      headerTaps: {
        panes,
        currentTab: { key },
      }
    } = props;
    const route = targetKey.split('~')
    if (route[0] === key) {
      // 表示删除得tab跟打开得tab一样
      panes.map((item, index) => {
        if (item.key === route[0]) {
          if (index === 0) {
            if (panes.length > 1) {
              router.push({
                pathname: panes[1].path,
                query: panes[1].query
              });
            } else {
              router.push({
                pathname: panes[0].path,
                query: panes[0].query
              });
            }
          } else {
            if (panes.length) {
              router.push({
                pathname: panes[index - 1].path,
                query: panes[index - 1].query
              });
            }
          }
        }
      });
    }
    const pathArr = route[0].split('/').filter(item => item !== '').join('_')
    dispatch({
      type: 'commonAction/uploadCatch',
      payload: {
        catchObj: {
          [pathArr]: [false, true]
        }
      }
    })
    // update dva
    const panesList = panes.filter(pane => pane.key !== route[0]); // 非当前点击 剩余得对象 数组
    dispatch({
      type: 'headerTaps/updateHeaderTaps',
      payload: { panes: panesList },
    });
  };
  const {
    headerTaps: {
      panes,
      currentTab: { key },
    },
  } = props;

  return (
    <div className="HeaderTabs">
      <Tabs
        hideAdd
        onChange={onChange}
        activeKey={key}
        type="editable-card"
        onEdit={(targetKey, a) => onEdit(targetKey, a)}
      >
        {panes.map(pane => (
          <TabPane
            key={pane.key}
            tab={<span style={{ fontSize: '14px' }}>{pane.title}</span>}
          >
            {pane.content}
          </TabPane>
        ))}
      </Tabs>
    </div>
  );
}

export default connect(({ headerTaps, commonAction }) => ({
  headerTaps,commonAction
}))(withRouter(HeaderTabs));
